package com.gxuwz.Market.business.action.web;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gxuwz.Market.business.entity.ServiceBranch;
import com.gxuwz.Market.business.entity.ServiceData;
import com.gxuwz.Market.business.entity.ServiceField;
import com.gxuwz.Market.business.entity.ServiceForm;
import com.gxuwz.Market.business.entity.ServiceRecord;
import com.gxuwz.Market.business.entity.ServiceTask;
import com.gxuwz.Market.business.entity.SysUser;
import com.gxuwz.Market.business.service.IServiceBranchService;
import com.gxuwz.Market.business.service.IServiceDataService;
import com.gxuwz.Market.business.service.IServiceFormService;
import com.gxuwz.Market.business.service.IServiceRecordService;
import com.gxuwz.Market.business.service.IServiceTaskService;
import com.gxuwz.Market.business.service.ISysUserService;
import com.gxuwz.core.pagination.Result;
import com.gxuwz.core.util.UidUtils;
import com.gxuwz.core.web.action.BaseAction;
import com.mysql.fabric.xmlrpc.base.Data;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import util.ExcelUtil;
import util.MyTime;


public class ServiceTaskAction extends BaseAction implements Preparable, ModelDriven<ServiceTask> {

	protected static final String LIST_JSP = "/WEB-INF/page/web/ServiceTask_list.jsp";  
	protected static final String ADD_JSP = "/WEB-INF/page/web/ServiceTask_add.jsp";
	protected static final String EDIT_JSP = "/WEB-INF/page/web/ServiceTask_edit.jsp";
	protected static final String DETAILS_JSP = "/WEB-INF/page/web/ServiceTask_details.jsp";
	protected static final String PREVIEW_JSP = "/WEB-INF/page/web/ServiceTask_preview.jsp";
	protected static final String MYTASK_JSP = "/WEB-INF/page/web/ServiceTask_my_task.jsp";
	protected static final String DATAEDIT_JSP = "/WEB-INF/page/web/ServiceData_edit.jsp";
	protected static final String AllUser_JSP = "/WEB-INF/page/web/SysUser_allUsers.jsp";
	
	@Autowired
	private IServiceTaskService serviceTaskService;
	@Autowired
	private IServiceDataService serviceDataService;
	@Autowired
	private IServiceFormService serviceFormService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IServiceRecordService serviceRecordService;
	@Autowired
	private IServiceBranchService serviceBranchService;
	
	private ServiceTask serviceTask;
	private Result<ServiceTask> pageResult;
	private ServiceData serviceData;
	private ServiceForm serviceForm;
	private ServiceRecord serviceRecord;
	
	private List<ServiceTask> taskList = new ArrayList<ServiceTask>();
	private List<ServiceData> dataList = new ArrayList<ServiceData>();
	private List<ServiceField> fieldList = new ArrayList<ServiceField>();
	private List<SysUser> SysUserList;
	
	private String[] filedNames;
	private String userids;  //用户编号字符串
	private String[] uids;	//用户编号数组
	
	private Map<String,String[]> fieldValue = new HashMap<String, String[]>();
	private Map<String,Integer> editMap = new HashMap<String, Integer>();//填写状态
	private Map<String,String> issuserMap = new HashMap<String, String>();//发布者名称
	private Map<String,String> stateMap = new HashMap<String, String>();//填写完成状态
	
	private Integer sign; //标志 0个人修改  1教师修改
	private String inBranch;	//是否同时添加联系人
	
	
	
	
	@Override
	public void prepare() throws Exception {
		if(null == serviceTask){
			serviceTask = new ServiceTask();
		}
		if(null == serviceData){
			serviceData = new ServiceData();
		}
	}

	@Override
	public ServiceTask getModel() {
		return serviceTask;
	}
	
	@Override
	public String execute() throws Exception {
		
		return SUCCESS;
	}

	

	
	/**
	 * 跳转到个人填写页面
	 * @return
	 */
	public String toDataEdit(){
		String writerId = (String)getRequest().getSession().getAttribute("userId");
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		serviceData = serviceDataService.findByWriterId(serviceTask.getDataName(), writerId, serviceForm.getFieldNum());
		
		String[] fieldNames = serviceForm.getFieldNames().split(",");
		String[] fieldLens = serviceForm.getFieldLen().split(",");
		String[] fieldType = serviceForm.getFieldType().split(",");
		String[] fieldValue = serviceData.getDatas();
		for(int i=0;i<serviceForm.getFieldNum();i++){
			ServiceField field = new ServiceField();
			field.setName(fieldNames[i]);
			field.setLen(fieldLens[i]);
			field.setType(fieldType[i]);
			field.setValue(fieldValue[i]);
			
			fieldList.add(field);
		}
		sign = 0;
		setForwardView(DATAEDIT_JSP);
		return SUCCESS;
	}
	/**
	 * 教师修改学生数据
	 */
	public String tchDataEdit() {
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		serviceData = serviceDataService.findByWriterId(serviceTask.getDataName(), serviceData.getWriterId(), serviceForm.getFieldNum());
		String[] fieldNames = serviceForm.getFieldNames().split(",");
		String[] fieldLens = serviceForm.getFieldLen().split(",");
		String[] fieldType = serviceForm.getFieldType().split(",");
		String[] fieldValue = serviceData.getDatas();
		for(int i=0;i<serviceForm.getFieldNum();i++){
			ServiceField field = new ServiceField();
			field.setName(fieldNames[i]);
			field.setLen(fieldLens[i]);
			field.setType(fieldType[i]);
			field.setValue(fieldValue[i]);
			
			fieldList.add(field);
		}
		sign = 1;
		setForwardView(DATAEDIT_JSP);
		return SUCCESS;
	}
	
	
	/**
	 * 跳转到填写页面
	 * @return
	 */
	public String recordToDataEdit(){
		serviceRecord = serviceRecordService.findById(serviceRecord.getId());
		
		String writerId = (String)getRequest().getSession().getAttribute("userId");
		serviceForm = serviceFormService.findByProperty("formId", serviceRecord.getFormId()).get(0);
		serviceData = serviceDataService.findByWriterId(serviceRecord.getDataName(), writerId, 3);
		
		String[] fieldNames = serviceForm.getFieldNames().split(",");
		String[] fieldLens = serviceForm.getFieldLen().split(",");
		String[] fieldType = serviceForm.getFieldType().split(",");
		String[] fieldValue = serviceData.getDatas();
		for(int i=0;i<serviceForm.getFieldNum();i++){
			ServiceField field = new ServiceField();
			field.setName(fieldNames[i]);
			field.setLen(fieldLens[i]);
			field.setType(fieldType[i]);
			field.setValue(fieldValue[i]);
			
			fieldList.add(field);
		}
		
		setForwardView(DATAEDIT_JSP);
		return SUCCESS;
	}
	
	
	/**
	 * 修改填写数据
	 * @return
	 */
	public String dataEdit(){
		//修改个人数据
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		serviceDataService.update(serviceTask.getDataName(), serviceData);
		//保存修改记录
		ServiceRecord record = new ServiceRecord();
		record.setDataName(serviceTask.getDataName());
		record.setEditTime(MyTime.getNowForTimestamp());
		record.setFormId(serviceTask.getFormId());
		record.setFormName(serviceTask.getTaskName());
		record.setWriterId((String)getRequest().getSession().getAttribute("userId"));
		
		serviceRecordService.add(record);
		if(sign == 1){
			serviceData = new ServiceData();
			return openDetails();
		}else{
			return myTask();
		}
		
	}
	
	//导出成excel
	public void toExcel(){
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		try{
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		serviceData = new ServiceData();
		serviceData.setDataState(1);
		List<ServiceData> dList = serviceDataService.find(serviceTask.getDataName(), serviceForm.getFieldNum(), serviceData);
		try {
			//获得表格对象
			HSSFWorkbook wb = ExcelUtil.ListToExcel(serviceForm, dList);
			//不弹出下载框的写法
			/*FileOutputStream out =new FileOutputStream("E://"+serviceTask.getTaskName()+".xls");
			wb.write(out); 
			out.close();*/
			//弹出下载框
			String fileName = serviceTask.getTaskName();
		      ByteArrayOutputStream os = new ByteArrayOutputStream();
		      wb.write(os);
		      byte[] content = os.toByteArray();
		      HttpServletResponse res = ServletActionContext.getResponse();
		      InputStream is = new ByteArrayInputStream(content);
		      // 设置response参数，可以打开下载页面
		      res.reset();
		      res.setContentType("application/vnd.ms-excel;charset=utf-8");
		      res.setHeader("Content-Disposition", "attachment;filename="
		          + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		      ServletOutputStream out = res.getOutputStream();
		      BufferedInputStream bis = null;
		      BufferedOutputStream bos = null;
		 
		      try {
		        bis = new BufferedInputStream(is);
		        bos = new BufferedOutputStream(out);
		        byte[] buff = new byte[2048];
		        int bytesRead;
		        // Simple read/write loop.
		        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		          bos.write(buff, 0, bytesRead);
		        }
		      } catch (Exception e) {
		        // TODO: handle exception
		        e.printStackTrace();
		      } finally {
		        if (bis != null)
		          bis.close();
		        if (bos != null)
		          bos.close();
		      }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	
	/**
	 * 我的任务页面
	 * @return
	 */
	public String myTask(){
		//获取登录人id
		String userId = (String)getRequest().getSession().getAttribute("userId");
		//查询状态为未完成的任务
		List<ServiceTask> tList = serviceTaskService.findByState(0);
		
		for(ServiceTask t: tList){
			ServiceData sd = serviceDataService.findByWriterId(t.getDataName(), userId, 0);
			
			if(sd != null){
				//保存是否填写
				editMap.put(t.getTaskId(), sd.getDataState());
				//保存任务创建人名称
				issuserMap.put(t.getTaskId(), sysUserService.findByProperty("userId", t.getIssuserId()).get(0).getUserName());
				//显示次任务
				taskList.add(t);
			}
		}
	
		
		setForwardView(MYTASK_JSP);
		return SUCCESS;
	}
	
	/**
	 * 打开列表页面
	 * @return
	 */
	public String openList(){
		pageResult = serviceTaskService.find(serviceTask, getPage(), getRow());
		List<ServiceTask> taskList = pageResult.getData();
		for(ServiceTask task:taskList){
			String finish = serviceDataService.finish(task.getDataName());
			stateMap.put(task.getTaskId(), finish);
		}
		setForwardView(LIST_JSP);
		return SUCCESS;
	}


	/**
	 * 打开任务修改页面
	 * @return
	 */
	public String openEdit(){
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		setForwardView(EDIT_JSP);
		return SUCCESS;
	}
	/**
	 * 任务已填写详情
	 * @return
	 */
	public String openDetails(){
		//查询出任务信息
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		//查询出格式信息
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		//获取字段名
		filedNames = serviceForm.getFieldNames().split(",");
		//查询出数据信息
		dataList = serviceDataService.find(serviceTask.getDataName(), serviceForm.getFieldNum(),serviceData);
		
		setForwardView(DETAILS_JSP);
		return SUCCESS;
	}
	
	/**
	 * 任务预览
	 * @return
	 */
	public String preview(){
		//查询出任务信息
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		//查询出格式信息
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		//获取字段名
		filedNames = serviceForm.getFieldNames().split(",");
		//查询出数据信息
		dataList = serviceDataService.find(serviceTask.getDataName(), serviceForm.getFieldNum(),serviceData);
		
		setForwardView(PREVIEW_JSP);
		return SUCCESS;
	}
	/**
	 * 打开添加任务页面
	 * @return
	 */
	public String openAdd() {
		serviceForm = serviceFormService.findById(serviceForm.getId());
		setForwardView(ADD_JSP);
		return SUCCESS;
	}
	/**
	 * 添加任务
	 * @return
	 */
	public String add() {
		serviceForm = serviceFormService.findById(serviceForm.getId());
		serviceTask.setStartTime(new Timestamp(new Date().getTime()));
		serviceTask.setTaskId(UidUtils.MINIUID());
		serviceTask.setIssuserId((String)getRequest().getSession().getAttribute("userId"));
		serviceTask.setFormId(serviceForm.getFormId());
		serviceTask.setTaskState(0);
		serviceTask.setTaskType(0);
		serviceTask.setDataName("service_"+serviceTask.getTaskId()+"_data");
		serviceTaskService.add(serviceTask);
		serviceForm.setFormState(1);
		serviceFormService.update(serviceForm);
		serviceDataService.createDB(serviceTask.getTaskId(), serviceForm);
		return toAddWriter();
	}
	
	public String toAddWriter(){
		serviceTask = serviceTaskService.findByProperty("taskId", serviceTask.getTaskId()).get(0);
		SysUserList = sysUserService.findAll();	
		setForwardView(AllUser_JSP);
		return SUCCESS;
	}
	
	/**
	 * 删除任务
	 * @return
	 */
	public String delete() {
		serviceTaskService.delete(serviceTask.getId());
		serviceTask = new ServiceTask();
		return openList();
	}
	
	/**
	 * 删除数据
	 * @return
	 */
	public String delData() {
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		serviceDataService.delete(serviceTask.getDataName(), serviceData.getId());
		return openDetails();
	}
	
	/**
	 * 添加填写人
	 * @return
	 */
	public String addWriter() {
		List<String> us = new ArrayList<String>();

		try{
			//向数据表中添加数据
			if(uids != null && !uids.equals("")){
				List<String> sl = Arrays.asList(uids);
				us = new ArrayList<String>(sl);

			}

			if(inBranch != null){
				String userId = (String)getRequest().getSession().getAttribute("userId");
				List<ServiceBranch> branchList = serviceBranchService.findByProperty("parentId", userId);
				List<SysUser> userList = sysUserService.findByBranch(branchList);
				if(userList != null && userList.size()>0){
					for(SysUser user : userList){
						if(!us.contains(user)){
							us.add(user.getUserId());
						}
						
					}
				}
			
			}
			serviceTask = serviceTaskService.findByProperty("taskId", serviceTask.getTaskId()).get(0);
			if(us.size()>0){
				serviceDataService.addWriter(serviceTask.getTaskId(), us);
			}
		}catch(Exception e){
			System.out.println(e);
		}
		
		
		
		return openDetails();
	}
	
	public String toEdit(){
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		
		setForwardView(EDIT_JSP);
		return SUCCESS;
	}
	
	public String edit(){
		ServiceTask task = serviceTaskService.findById(serviceTask.getId());
		task.setEndTime(serviceTask.getEndTime());
		task.setRemark(serviceTask.getRemark());
		task.setTaskName(serviceTask.getTaskName());
		task.setTaskState(serviceTask.getTaskState());
		serviceTaskService.update(task);
		
		serviceTask = new ServiceTask();
		return openList();
	}
	
	public ServiceTask getServiceTask() {
		return serviceTask;
	}

	public void setServiceTask(ServiceTask serviceTask) {
		this.serviceTask = serviceTask;
	}

	public Result<ServiceTask> getPageResult() {
		return pageResult;
	}

	public void setPageResult(Result<ServiceTask> pageResult) {
		this.pageResult = pageResult;
	}

	public ServiceData getServiceData() {
		return serviceData;
	}

	public void setServiceData(ServiceData serviceData) {
		this.serviceData = serviceData;
	}

	public List<ServiceTask> getTaskList() {
		return taskList;
	}

	public void setTaskList(List<ServiceTask> taskList) {
		this.taskList = taskList;
	}

	public ServiceForm getServiceForm() {
		return serviceForm;
	}

	public void setServiceForm(ServiceForm serviceForm) {
		this.serviceForm = serviceForm;
	}

	public List<ServiceData> getDataList() {
		return dataList;
	}

	public void setDataList(List<ServiceData> dataList) {
		this.dataList = dataList;
	}

	public String[] getFiledNames() {
		return filedNames;
	}

	public void setFiledNames(String[] filedNames) {
		this.filedNames = filedNames;
	}

	public List<ServiceField> getFieldList() {
		return fieldList;
	}

	public void setFieldList(List<ServiceField> fieldList) {
		this.fieldList = fieldList;
	}

	public Map<String, String[]> getFieldValue() {
		return fieldValue;
	}

	public void setFieldValue(Map<String, String[]> fieldValue) {
		this.fieldValue = fieldValue;
	}

	public Map<String, Integer> getEditMap() {
		return editMap;
	}

	public void setEditMap(Map<String, Integer> editMap) {
		this.editMap = editMap;
	}

	public Map<String, String> getIssuserMap() {
		return issuserMap;
	}

	public void setIssuserMap(Map<String, String> issuserMap) {
		this.issuserMap = issuserMap;
	}

	public ServiceRecord getServiceRecord() {
		return serviceRecord;
	}

	public void setServiceRecord(ServiceRecord serviceRecord) {
		this.serviceRecord = serviceRecord;
	}

	public List<SysUser> getSysUserList() {
		return SysUserList;
	}

	public void setSysUserList(List<SysUser> sysUserList) {
		SysUserList = sysUserList;
	}

	public String getUserids() {
		return userids;
	}

	public void setUserids(String userids) {
		this.userids = userids;
	}

	public String[] getUids() {
		return uids;
	}

	public void setUids(String[] uids) {
		this.uids = uids;
	}

	public Integer getSign() {
		return sign;
	}

	public void setSign(Integer sign) {
		this.sign = sign;
	}

	public Map<String, String> getStateMap() {
		return stateMap;
	}

	public void setStateMap(Map<String, String> stateMap) {
		this.stateMap = stateMap;
	}

	public String getInBranch() {
		return inBranch;
	}

	public void setInBranch(String inBranch) {
		this.inBranch = inBranch;
	}

	
}
